
import 'package:flutter/widgets.dart';
import 'package:library_base/entities/suppliers_entity.dart';
import 'package:library_base/provider/base_controller.dart';
import 'package:get/get.dart';
import 'package:lpinyin/lpinyin.dart';
import 'package:azlistview/azlistview.dart';


class ChooseSupplierController extends BaseController{

  RxList<SuppliersEntity> cityList = <SuppliersEntity>[].obs;

  RxList<SuppliersEntity> cityListWithKeyWord = <SuppliersEntity>[].obs;

  Rxn<SuppliersEntity?> suppliersEntity = Rxn<SuppliersEntity?>();

  int selectedPosition = -1;

  int selectedIfWordIsEmptyPosition = -1;

  Rx<String> keyWord = ''.obs;

  Rx<bool> isAction = false.obs;

  final TextEditingController keyWorkSearchController = TextEditingController();

  @override
  void onCreate() {

    var argumentMap = Get.arguments as Map<String,dynamic>;

    cityList.value = argumentMap['Supplier'] as List<SuppliersEntity>;

    suppliersEntity.value = argumentMap['SelectedSupplier'] as SuppliersEntity?;

    _handleList(cityList);

    if(suppliersEntity.value!=null){
      var selectedSuppliersEntity  = cityList.firstWhere((element) => element.id == suppliersEntity.value!.id);
      selectedSuppliersEntity.isSelect = true;
      suppliersEntity.value = selectedSuppliersEntity;
      selectedPosition = cityList.indexOf(selectedSuppliersEntity);
    }

  }

  void _handleList(List<SuppliersEntity> list) {
    if (list.isEmpty) return;
    for (int i = 0, length = list.length; i < length; i++) {
      String pinyin = PinyinHelper.getPinyinE(list[i].name);
      String tag = pinyin.substring(0, 1).toUpperCase();
      list[i].namePinyin = pinyin;
      if (RegExp('[A-Z]').hasMatch(tag)) {
        list[i].tagIndex = tag;
      } else {
        list[i].tagIndex = '#';
      }
    }

    // A-Z sort.
    SuspensionUtil.sortListBySuspensionTag(list);

    for (var element in cityList) {
      if(suppliersEntity.value == element){
        element.isSelect = true;
      }
    }
    // show sus tag.
    SuspensionUtil.setShowSuspensionStatus(cityList);

    update();
  }

}